﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using InformationSystem.BLL.Core.Model;
using System.IO;
using InformationSystem.BLL.Core.Service;
using InformationSystem.WebSite.Utility;

namespace InformationSystem.WebSite.Module.NoticeMgr
{
    public partial class CreateNew : BasePage
    {
        protected LoginUser user;
        public IInformationService InformationService;
        protected void Page_Load(object sender, EventArgs e)
        {
            user = (LoginUser)Session["LoginUser"];
            if (!X.IsAjaxRequest)
            {
                //根据权限控制创建的内容
                if (user.LoginUserType == UserType.Student || user.LoginUserType == UserType.Parent)
                {
                    cmpublicinfo.Hide();
                    cmworkinfo.Hide();
                }
                else if (user.LoginUserType == UserType.Admin)
                {
                    cmworkinfo.Hide();
                }
                //根据传入参数，显示类型
                if (Request.QueryString["m"] != null)
                {
                    string mtype = Request.QueryString["m"];
                    int id = 0;
                    if (Request.QueryString["id"] != null)
                        int.TryParse(Request.QueryString["id"], out id);
                    if (mtype != string.Empty)
                    {
                        switch (mtype.ToLower())
                        {
                            case "mail":
                                //邮件
                                cmMail.Checked = true;
                                myid.Value = "cmMail";
                                if (id != 0)
                                {
                                    needresize.Value = "1";
                                    //init source mail
                                    Mail mail = InformationService.GetMailDetailByID(id, user.UserID);
                                    if (mail.Msg == string.Empty)
                                    {
                                        this.txtsubject.Text = "回复:" + mail.MailSubject;
                                        this.txtto.Text = mail.SendUserName + "[" + mail.SendUserID + "]";
                                        this.txtContent.Text = "<br><br><br><br><br>--------------<br>" + mail.Content;
                                    }
                                }
                                break;
                            case "publicinfo":
                                //公告
                                if (user.LoginUserType == UserType.Admin || user.LoginUserType == UserType.Assistant)
                                {
                                    cmpublicinfo.Checked = true;
                                    myid.Value = "cmpublicinfo";
                                }
                                break;
                            case "workinfo":
                                //就业信息
                                if (user.LoginUserType == UserType.Assistant)
                                {
                                    cmworkinfo.Checked = true;
                                    myid.Value = "cmworkinfo";
                                }
                                break;
                            case "msg":
                                cmMsg.Checked = true;
                                myid.Value = "cmMsg";
                                //消息
                                break;
                        }
                    }
                }
            }
        }


        protected void btnSend_Click(object sender, DirectEventArgs e)
        {
            //发送权限检查
            if (!this.CommitPermissionCheck())
            {
                X.Msg.Show(new MessageBoxConfig
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.INFO,
                    Title = "信息",
                    Message = "你没有操作权限,请联系管理员！"
                });
                return;
            }

            //Do Logic
            this.SendProgess();

        }

        protected void btnSave_Click(object sender, DirectEventArgs e)
        {
            //发送权限检查
            if (!this.CommitPermissionCheck())
            {
                X.Msg.Show(new MessageBoxConfig
                {
                    Buttons = MessageBox.Button.OK,
                    Icon = MessageBox.Icon.INFO,
                    Title = "信息",
                    Message = "你没有操作权限,请联系管理员！"
                });
                return;
            }

        }

        private void SendProgess()
        {
            string outmsg = string.Empty;
            string savePath = string.Empty;

            List<Attachment> uploadfiles = this.GetAttachmentInfos();

            if (cmMail.Checked)
            {
                savePath = Path.Combine(Server.MapPath("~"), Common.MailAttachmentPath);
                Mail newmail = this.AssembleMailInfo(uploadfiles);
                //send Mail
                bool sendresultOK = InformationService.SendMail(newmail);
                if (!sendresultOK)
                {
                    X.Msg.Show(new MessageBoxConfig
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.INFO,
                        Title = "信息",
                        Message = string.Format("邮件发送失败，存在如下问题:{0}", newmail.Msg)
                    });
                    return;
                }
                string outputmsg = string.Empty;
                if (newmail.Msg != string.Empty)
                    outputmsg = newmail.Msg;
                //Save Attachment
                if (!this.SaveFiles(savePath, uploadfiles, out outmsg))
                {
                    outputmsg += outmsg;
                }
                if (outputmsg != string.Empty)
                {
                    X.Msg.Show(new MessageBoxConfig
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.INFO,
                        Title = "信息",
                        Message = string.Format("邮件发送成功，但存在如下问题:{0}", outputmsg)
                    });
                }
                else
                {
                    X.Msg.Show(new MessageBoxConfig
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.INFO,
                        Title = "信息",
                        Message = "邮件发送成功"
                    });
                }
                return;
            }
            else if (cmMsg.Checked)
            {
                savePath = Path.Combine(Server.MapPath("~"), Common.MsgAttachmentPath);

                Msg newmsg = this.AssembleMsgInfo(uploadfiles);

                bool sendresultOK = InformationService.SendMsg(newmsg);
                if (!sendresultOK)
                {
                    X.Msg.Show(new MessageBoxConfig
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.INFO,
                        Title = "信息",
                        Message = string.Format("信息发送失败，存在如下问题:{0}", newmsg.Msg)
                    });
                    return;
                }
                string outputmsg = string.Empty;
                if (newmsg.Msg != string.Empty)
                    outputmsg = newmsg.Msg;
                //Save Attachment
                if (!this.SaveFiles(savePath, uploadfiles, out outmsg))
                {
                    outputmsg += outmsg;
                }
                if (outputmsg != string.Empty)
                {
                    X.Msg.Show(new MessageBoxConfig
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.INFO,
                        Title = "信息",
                        Message = string.Format("信息发送成功，但存在如下问题:{0}", outputmsg)
                    });
                }
                else
                {
                    X.Msg.Show(new MessageBoxConfig
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.INFO,
                        Title = "信息",
                        Message = "信息发送成功！"
                    });
                }
                return;
            }
            else if (cmpublicinfo.Checked)
            {
                savePath = Path.Combine(Server.MapPath("~"), Common.AfficheAttachmentPath);

                Affiche newaffiche = this.AssembleAfficheInfo(uploadfiles);
                //send publicinfo
                bool sendresultOK = InformationService.SendAffiche(newaffiche);

                string outputmsg = string.Empty;

                //Save Attachment
                if (!this.SaveFiles(savePath, uploadfiles, out outmsg))
                {
                    outputmsg += outmsg;
                }
                if (outputmsg != string.Empty)
                {
                    X.Msg.Show(new MessageBoxConfig
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.INFO,
                        Title = "信息",
                        Message = string.Format("公告发送成功，但存在如下问题:{0}", outputmsg)
                    });
                }
                else
                {
                    X.Msg.Show(new MessageBoxConfig
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.INFO,
                        Title = "信息",
                        Message = "公告发送成功！"
                    });
                }
                return;
            }
            else if (cmworkinfo.Checked)
            {
                savePath = Path.Combine(Server.MapPath("~"), Common.WorkAttachmentPath);
                WorkInfo newwork = this.AssembleWorkInfo(uploadfiles);

                //send workInfo
                bool sendresultOK = InformationService.SendWorkInfo(newwork);

                string outputmsg = string.Empty;

                //Save Attachment
                if (!this.SaveFiles(savePath, uploadfiles, out outmsg))
                {
                    outputmsg += outmsg;
                }
                if (outputmsg != string.Empty)
                {
                    X.Msg.Show(new MessageBoxConfig
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.INFO,
                        Title = "信息",
                        Message = string.Format("就业信息发送成功，但存在如下问题:{0}", outputmsg)
                    });
                }
                else
                {
                    X.Msg.Show(new MessageBoxConfig
                    {
                        Buttons = MessageBox.Button.OK,
                        Icon = MessageBox.Icon.INFO,
                        Title = "信息",
                        Message = "就业信息发送成功！"
                    });
                }
                return;
            }
        }


        private List<Attachment> GetAttachmentInfos()
        {
            HttpFileCollection coll = Request.Files;
            List<Attachment> attlist = null;
            if (coll != null)
            {
                attlist = new List<Attachment>();
                for (int i = 0; i < coll.Count; i++)
                {
                    if (coll[i].ContentLength > 0 && coll[i].FileName != string.Empty)
                    {
                        Attachment atta = new Attachment();
                        atta.FileID = i;
                        atta.SavedFileName = Guid.NewGuid().ToString() + Path.GetExtension(coll[i].FileName);
                        atta.UploadFileName = Path.GetFileName(coll[i].FileName);
                        attlist.Add(atta);
                    }
                }
            }
            return attlist;
        }

        private bool SaveFiles(string savePath, List<Attachment> attalist, out string savelog)
        {
            savelog = string.Empty;
            HttpFileCollection coll = Request.Files;
            try
            {
                foreach (var item in attalist)
                {
                    coll[item.FileID].SaveAs(Path.Combine(savePath, item.SavedFileName));
                }
            }
            catch (Exception ex)
            {
                savelog = ex.Message;
                return false;
            }
            return true;
        }

        private WorkInfo AssembleWorkInfo(List<Attachment> uploadfiles)
        {
            WorkInfo workInfo = new WorkInfo();
            workInfo.AttachmentList = uploadfiles;
            workInfo.CollegeID = user.CollegeID;
            workInfo.CommitUserID = user.UserID;
            workInfo.CommitUserName = user.UserName;
            workInfo.Content = StringCheck.GetSafeContent(txtContent.Text);
            workInfo.GradeID = user.GradeID;
            if (uploadfiles != null && uploadfiles.Count > 0)
                workInfo.HasAttachment = true;
            else
                workInfo.HasAttachment = false;
            workInfo.IsPublicToCollege = false;
            workInfo.KeyWord = HttpUtility.HtmlEncode(txtkey.Text);
            workInfo.SendTime = DateTime.Now;
            workInfo.Title = HttpUtility.HtmlEncode(txtsubject.Text);
            workInfo.WorkInfoID = 0;
            return workInfo;
        }

        private Affiche AssembleAfficheInfo(List<Attachment> uploadfiles)
        {
            Affiche affiche = new Affiche();
            affiche.AfficheID = 0;
            affiche.CollegeID = user.CollegeID;
            affiche.CommitUserID = user.UserID;
            affiche.CommitUserName = user.UserName;
            affiche.Content = StringCheck.GetSafeContent(this.txtContent.Text);
            affiche.GradeID = user.GradeID;
            affiche.IsPublicToCollege = false;
            affiche.KeyWord = HttpUtility.HtmlEncode(this.txtkey.Text);
            affiche.Title = HttpUtility.HtmlEncode(this.txtsubject.Text);
            affiche.SendTime = DateTime.Now;
            if (uploadfiles != null && uploadfiles.Count > 0)
                affiche.HasAttachment = true;
            else
                affiche.HasAttachment = false;
            affiche.AttachmentList = uploadfiles;
            return affiche;
        }

        private Msg AssembleMsgInfo(List<Attachment> uploadfiles)
        {
            Msg msg = new Msg();
            msg.AttachmentList = uploadfiles;
            msg.Content = StringCheck.GetSafeContent(txtContent.Text);
            if (uploadfiles != null && uploadfiles.Count > 0)
                msg.HasAttachment = true;
            else
                msg.HasAttachment = false;
            msg.KeyWord = HttpUtility.HtmlEncode(txtkey.Text);
            msg.MsgID = 0;
            msg.RecvString = txtto.Text;
            msg.SendTime = DateTime.Now;
            msg.SendUserID = user.UserID;
            msg.SendUserName = user.UserName;
            msg.Subject = HttpUtility.HtmlEncode(txtsubject.Text);
            return msg;
        }

        private Mail AssembleMailInfo(List<Attachment> uploadfiles)
        {
            Mail mail = new Mail();
            mail.MailSubject = HttpUtility.HtmlEncode(this.txtsubject.Text);
            mail.RecvString = this.txtto.Text;

            if (uploadfiles != null && uploadfiles.Count > 0)
                mail.HasAttachment = true;
            else
                mail.HasAttachment = false;
            mail.AttachmentList = uploadfiles;
            mail.MailID = 0;
            mail.MailStatus = MailStatus.Sent;
            mail.SendUserID = user.UserID;
            mail.SendUserName = user.UserName;
            mail.Content = StringCheck.GetSafeContent(txtContent.Text);
            mail.CreateTime = DateTime.Now;
            mail.SendTime = DateTime.Now;
            return mail;
        }

        protected override bool CommitPermissionCheck()
        {
            if (cmpublicinfo.Checked)
            {
                if (user.LoginUserType == UserType.Admin || user.LoginUserType == UserType.Assistant)
                    return true;
                else
                    return false;
            }
            else if (cmworkinfo.Checked)
            {
                if (user.LoginUserType == UserType.Assistant)
                    return true;
                else
                    return false;
            }
            else if (cmMail.Checked || cmMsg.Checked)
            {
                return true;
            }
            return false;
        }
    }
}